module time_manager

    use common_info
    use message
    use run_manager

    implicit none

    integer :: nt
    real :: dt
    real :: end_time
    real :: cur_time

    logical, private :: initialized = .false.

    namelist /time_manager_parameters/ &
        dt, end_time

contains

    logical function time_manager_initialized result(res)
        res = initialized
    end function time_manager_initialized

    subroutine time_manager_init(namelist_file)
        character(*), intent(in) :: namelist_file

        character(50) :: config_str(2)

        ! module dependencies
        if(.not. common_info_is_initialized()) then
            call message_show(ERROR_MSG,    &
                "time_manager",             &
                "time_manager_init",        &
                """time_manager"" needs "   &
                // """common_info"" to be " &
                // "initialized first")
            call run_manager_end_run
        end if

        if(initialized) return

        open(10, file=namelist_file)
        read(10, nml=time_manager_parameters)
        close(10)

        nt = 0
        cur_time = 0.0

        initialized = .true.

        return
    end subroutine time_manager_init

    logical function time_manager_is_first_step result(res)
        if(nt == 0) then
            res = .true.
        else
            res = .false.
        end if
    end function time_manager_is_first_step

    logical function time_manager_continue result(res)
        if(cur_time < end_time) then
           res = .true.
        else
           res = .false.
        end if 
    end function time_manager_continue
            
    subroutine time_manager_advance
        nt = nt+1
        cur_time = cur_time+dt
    end subroutine time_manager_advance

    function time_manager_cur_time_string result(res)
        character(10) :: res

        write(res, "(f10.4)") cur_time
        res = trim(adjustl(res))

        return
    end function time_manager_cur_time_string 

end module time_manager
